let users = [];
let departments = [];
let currentUser = null;
let isEditMode = false;
let currentUserId = null;
let currentPage = 1;
let pageSize = 10;
let filteredUsers = [];
let manageableDepartments = []; // 可管理的部门ID列表

// 页面加载完成后初始化

document.addEventListener('DOMContentLoaded', async function() {
    
    if (window.AuthManager && window.AuthManager.getUserInfo()) {
        window.PermissionManager.init(window.AuthManager.getUserInfo());
    }
    // JWT认证检查
    if (!window.AuthManager || !AuthManager.isAuthenticated()) {
        showAccessDenied();
        return;
    }
    // 检查token有效性
    try {
        await AuthManager.verifyToken();
    } catch (e) {
        showAccessDenied();
        return;
    }
    loadCurrentUser();
    if (window.PermissionManager) {
        PermissionManager.initUserPermissions();
    }
});

// 加载当前用户信息
async function loadCurrentUser() {
    try {
        const headers = new Headers(AuthManager.getAuthHeaders());
        const response = await fetch('/ercms/api/users/current', {
            headers
        });
        if (response.ok) {
            currentUser = await response.json();
            if (hasUserManagementAccess()) {
                setupUserManagement();
            } else {
                showAccessDenied();
            }
        } else {
            showAccessDenied();
        }
    } catch (error) {
        console.error('加载当前用户信息失败：', error);
        showAccessDenied();
    }
}

// 检查是否有用户管理权限
function hasUserManagementAccess() {
    if (!currentUser) return false;
    return currentUser.role === 'ADMIN' || currentUser.role === 'DEPT_MANAGER';
}

// 显示访问被拒绝页面
function showAccessDenied() {
    document.getElementById('accessDenied').style.display = 'block';
    document.getElementById('userManagementContent').style.display = 'none';
}

// 设置用户管理功能
function setupUserManagement() {
    document.getElementById('accessDenied').style.display = 'none';
    document.getElementById('userManagementContent').style.display = 'block';
    // 设置权限
    setupPermissions();
    // 加载数据
    loadUsers();
    loadDepartments();
}

// 设置权限
function setupPermissions() {
    const createUserBtn = document.getElementById('createUserBtn');
    const userScopeInfo = document.getElementById('userScopeInfo');
    if (currentUser) {
        if (currentUser.role === 'ADMIN') {
            createUserBtn.style.display = 'inline-block';
            userScopeInfo.textContent = '全部用户';
            userScopeInfo.style.display = 'inline-block';
        } else if (currentUser.role === 'DEPT_MANAGER') {
            createUserBtn.style.display = 'inline-block';
            userScopeInfo.textContent = '部门用户';
            userScopeInfo.style.display = 'inline-block';
            // 获取可管理的部门
            loadManageableDepartments();
        }
    }
}

// 加载可管理的部门（部门管理员）
async function loadManageableDepartments() {
    try {
        const response = await fetch(`/ercms/api/departments/user/${currentUser.id}/manageable`, {
            headers: AuthManager.getAuthHeaders()
        });
        const result = await response.json();
        if (result.success) {
            manageableDepartments = result.data.map(dept => dept.id);
        }
    } catch (error) {
        console.error('加载可管理部门失败：', error);
    }
}

// 显示加载状态
function showLoading() {
    const tbody = document.getElementById('userTableBody');
    tbody.innerHTML = `
        <tr>
            <td colspan="10" class="text-center text-muted">
                <div class="spinner-border spinner-border-sm me-2" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                加载中...
            </td>
        </tr>
    `;
}

// 显示错误状态
function showError(message) {
    const tbody = document.getElementById('userTableBody');
    tbody.innerHTML = `
        <tr>
            <td colspan="10" class="text-center text-danger">
                <i class="bi bi-exclamation-triangle me-2"></i>
                ${message}
                <button class="btn btn-outline-primary btn-sm ms-2" onclick="loadUsers()">
                    <i class="bi bi-arrow-clockwise"></i> 重试
                </button>
            </td>
        </tr>
    `;
}

// 加载用户数据
async function loadUsers() {
    showLoading();
    try {
        let url = '/ercms/api/users';
        // 如果是部门管理员，只加载可管理部门的用户
        if (currentUser && currentUser.role === 'DEPT_MANAGER') {
            url = `/ercms/api/users/by-departments?departmentIds=${manageableDepartments.join(',')}`;
        }
        const headers = new Headers(AuthManager.getAuthHeaders());
        const response = await fetch(url, {
            headers
        });
        if (response.ok) {
            const result = await response.json();
            if (result.success) {
                users = result.data;
                filteredUsers = [...users];
                renderUsers();
                populateFilters();
            } else {
                showError('加载用户数据失败：' + result.message);
            }
        } else {
            const error = await response.json();
            showError('加载用户数据失败：' + error.message);
        }
    } catch (error) {
        console.error('加载用户数据失败：', error);
        showError('网络错误，请检查网络连接');
    }
}

// 加载部门数据
async function loadDepartments() {
    try {
        const headers = new Headers(AuthManager.getAuthHeaders());
        const response = await fetch('/ercms/api/departments', {
            headers
        });
        const result = await response.json();
        if (result.success) {
            departments = result.data;
            populateDepartmentFilters();
        } else {
            console.error('加载部门数据失败：', result.message);
        }
    } catch (error) {
        console.error('加载部门数据失败：', error);
    }
}

// 渲染用户列表
function renderUsers() {
    const tbody = document.getElementById('userTableBody');
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pageUsers = filteredUsers.slice(startIndex, endIndex);
    if (pageUsers.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="10" class="text-center text-muted">
                    <i class="bi bi-inbox"></i> 暂无数据
                </td>
            </tr>
        `;
        return;
    }
    tbody.innerHTML = pageUsers.map(user => `
        <tr>
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>${user.realName}</td>
            <td>${user.email || '-'}</td>
            <td>${user.phone || '-'}</td>
            <td>
                <span class="badge bg-${getRoleBadgeColor(user.role)} role-badge">
                    ${getRoleDisplayName(user.role)}
                </span>
            </td>
            <td>${user.departmentName || '-'}</td>
            <td>
                <span class="badge bg-${user.enabled ? 'success' : 'danger'} status-badge">
                    ${user.enabled ? '启用' : '禁用'}
                </span>
            </td>
            <td>
                <span class="badge bg-${getStatusBadgeColor(user.status)} status-badge">
                    ${getStatusDisplayName(user.status)}
                </span>
            </td>
            <td>${new Date(user.createdAt).toLocaleString()}</td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-info" onclick="viewUser(${user.id})" title="查看详情">
                        <i class="bi bi-eye"></i>
                    </button>
                    ${canEditUser(user) ? `
                        <button class="btn btn-outline-primary" onclick="showEditUserModal(${user.id})" title="编辑">
                            <i class="bi bi-pencil"></i>
                        </button>
                    ` : ''}
                    ${canDeleteUser(user) ? `
                        <button class="btn btn-outline-danger" onclick="deleteUser(${user.id})" title="删除">
                            <i class="bi bi-trash"></i>
                        </button>
                    ` : ''}
                </div>
            </td>
        </tr>
    `).join('');
    renderPagination();
}

// 渲染分页
function renderPagination() {
    const totalPages = Math.ceil(filteredUsers.length / pageSize);
    const pagination = document.getElementById('pagination');
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    let paginationHtml = '';
    // 上一页
    paginationHtml += `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a>
        </li>
    `;
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            paginationHtml += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                </li>
            `;
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            paginationHtml += '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }
    // 下一页
    paginationHtml += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a>
        </li>
    `;
    pagination.innerHTML = paginationHtml;
}

// 切换页面
function changePage(page) {
    const totalPages = Math.ceil(filteredUsers.length / pageSize);
    if (page >= 1 && page <= totalPages) {
        currentPage = page;
        renderUsers();
    }
}

// 筛选器
function filterUsers() {
    const roleFilter = document.getElementById('roleFilter').value;
    const departmentFilter = document.getElementById('departmentFilter').value;
    const statusFilter = document.getElementById('statusFilter').value;
    const workStatusFilter = document.getElementById('workStatusFilter').value;
    const searchInput = document.getElementById('searchInput').value.toLowerCase();
    filteredUsers = users.filter(user => {
        // 角色筛选
        if (roleFilter && user.role !== roleFilter) return false;
        // 部门筛选
        if (departmentFilter && user.departmentId != departmentFilter) return false;
        // 状态筛选
        if (statusFilter && user.enabled.toString() !== statusFilter) return false;
        // 工作状态筛选
        if (workStatusFilter && user.status !== workStatusFilter) return false;
        // 搜索筛选
        if (searchInput) {
            const searchText = `${user.username} ${user.realName} ${user.email || ''}`.toLowerCase();
            if (!searchText.includes(searchInput)) return false;
        }
        return true;
    });
    currentPage = 1;
    renderUsers();
}

// 填充筛选器
function populateFilters() {
    // 部门筛选器已在 loadDepartments 中填充
}

// 填充部门筛选器
function populateDepartmentFilters() {
    const departmentFilter = document.getElementById('departmentFilter');
    const departmentSelect = document.getElementById('department');
    departmentFilter.innerHTML = '<option value="">全部部门</option>';
    departmentSelect.innerHTML = '<option value="">请选择部门</option>';
    // 如果是部门管理员，只显示可管理的部门
    const availableDepartments = currentUser && currentUser.role === 'DEPT_MANAGER' 
        ? departments.filter(dept => manageableDepartments.includes(dept.id))
        : departments;
    availableDepartments.forEach(dept => {
        const option = `<option value="${dept.id}">${dept.name}</option>`;
        departmentFilter.innerHTML += option;
        departmentSelect.innerHTML += option;
    });
}

// 显示创建用户模态框
function showCreateUserModal() {
    isEditMode = false;
    currentUserId = null;
    document.getElementById('userModalTitle').textContent = '创建用户';
    document.getElementById('userForm').reset();
    populateRoleOptions();
    const modal = new bootstrap.Modal(document.getElementById('userModal'));
    modal.show();
}

// 显示编辑用户模态框
function showEditUserModal(userId) {
    const user = users.find(u => u.id === userId);
    if (!user) return;
    isEditMode = true;
    currentUserId = userId;
    document.getElementById('userModalTitle').textContent = '编辑用户';
    populateRoleOptions();
    document.getElementById('username').value = user.username;
    document.getElementById('realName').value = user.realName;
    document.getElementById('email').value = user.email || '';
    document.getElementById('phone').value = user.phone || '';
    document.getElementById('role').value = user.role;
    document.getElementById('department').value = user.departmentId || '';
    document.getElementById('enabled').checked = user.enabled;
    // 编辑模式下密码可空
    document.getElementById('password').required = false;
    document.getElementById('confirmPassword').required = false;
    const modal = new bootstrap.Modal(document.getElementById('userModal'));
    modal.show();
}

// 填充角色选项
function populateRoleOptions() {
    const roleSelect = document.getElementById('role');
    roleSelect.innerHTML = '<option value="">请选择角色</option>';
    if (currentUser) {
        if (currentUser.role === 'ADMIN') {
            // 系统管理员可以创建所有角色
            roleSelect.innerHTML += `
                <option value="ADMIN">系统管理员</option>
                <option value="DEPT_MANAGER">部门管理员</option>
                <option value="DISPATCHER">调度员</option>
                <option value="END_USER">终端用户</option>
            `;
        } else if (currentUser.role === 'DEPT_MANAGER') {
            // 部门管理员只能创建终端用户
            roleSelect.innerHTML += `
                <option value="END_USER">终端用户</option>
            `;
        }
    }
}

// 保存用户
async function saveUser() {
    const formData = {
        username: document.getElementById('username').value,
        realName: document.getElementById('realName').value,
        email: document.getElementById('email').value,
        phone: document.getElementById('phone').value,
        role: document.getElementById('role').value,
        departmentId: document.getElementById('department').value || null,
        enabled: document.getElementById('enabled').checked
    };
    // 验证必填字段
    if (!formData.username.trim() || !formData.realName.trim() || !formData.role) {
        showErrorAlert('请填写必填字段');
        return;
    }
    // 验证密码
    if (!isEditMode) {
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        if (!password) {
            showErrorAlert('请输入密码');
            return;
        }
        if (password !== confirmPassword) {
            showErrorAlert('两次输入的密码不一致');
            return;
        }
        if (password.length < 6) {
            showErrorAlert('密码长度至少6个字符');
            return;
        }
        formData.password = password;
    }
    try {
        const url = isEditMode ? `/ercms/api/users/${currentUserId}` : '/ercms/api/users';
        const method = isEditMode ? 'PUT' : 'POST';
        const response = await fetch(url, {
            method: method,
            headers: AuthManager.getAuthHeaders(),
            body: JSON.stringify(formData)
        });
        const result = await response.json();
        if (result.success) {
            showSuccess(result.message);
            bootstrap.Modal.getInstance(document.getElementById('userModal')).hide();
            loadUsers();
        } else {
            showErrorAlert('操作失败：' + result.message);
        }
    } catch (error) {
        console.error('保存用户失败：', error);
        showErrorAlert('保存用户失败，请检查网络连接');
    }
}

// 查看用户详情
function viewUser(userId) {
    const user = users.find(u => u.id === userId);
    if (!user) return;
    const content = document.getElementById('userDetailContent');
    content.innerHTML = `
        <div class="row">
            <div class="col-md-6">
                <table class="table table-borderless">
                    <tr>
                        <td><strong>用户ID</strong></td>
                        <td>${user.id}</td>
                    </tr>
                    <tr>
                        <td><strong>用户名：</strong></td>
                        <td>${user.username}</td>
                    </tr>
                    <tr>
                        <td><strong>真实姓名</strong></td>
                        <td>${user.realName}</td>
                    </tr>
                    <tr>
                        <td><strong>邮箱</strong></td>
                        <td>${user.email || '-'}</td>
                    </tr>
                    <tr>
                        <td><strong>电话</strong></td>
                        <td>${user.phone || '-'}</td>
                    </tr>
                </table>
            </div>
            <div class="col-md-6">
                <table class="table table-borderless">
                    <tr>
                        <td><strong>角色</strong></td>
                        <td>
                            <span class="badge bg-${getRoleBadgeColor(user.role)}">
                                ${getRoleDisplayName(user.role)}
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td><strong>所属部门：</strong></td>
                        <td>${user.departmentName || '-'}</td>
                    </tr>
                    <tr>
                        <td><strong>状态：</strong></td>
                        <td>
                            <span class="badge bg-${user.enabled ? 'success' : 'danger'}">
                                ${user.enabled ? '启用' : '禁用'}
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td><strong>工作状态：</strong></td>
                        <td>
                            <span class="badge bg-${getStatusBadgeColor(user.status)}">
                                ${getStatusDisplayName(user.status)}
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td><strong>创建时间</strong></td>
                        <td>${new Date(user.createdAt).toLocaleString()}</td>
                    </tr>
                    <tr>
                        <td><strong>更新时间</strong></td>
                        <td>${new Date(user.updatedAt).toLocaleString()}</td>
                    </tr>
                </table>
            </div>
        </div>
    `;
    const modal = new bootstrap.Modal(document.getElementById('userDetailModal'));
    modal.show();
}

// 删除用户
async function deleteUser(userId) {
    const user = users.find(u => u.id === userId);
    const userName = user ? user.realName : '该用户';
    confirmAction(`确定要删除用户"${userName}"吗？删除后无法恢复。`, async () => {
        try {
            const response = await fetch(`/ercms/api/users/${userId}`, {
                method: 'DELETE',
                headers: AuthManager.getAuthHeaders()
            });
            const result = await response.json();
            if (result.success) {
                showSuccess(result.message);
                loadUsers();
            } else {
                showErrorAlert('删除失败：' + result.message);
            }
        } catch (error) {
            console.error('删除用户失败：', error);
            showErrorAlert('删除用户失败，请检查网络连接');
        }
    });
}

// 刷新用户列表
function refreshUsers() {
    loadUsers();
}

// 权限检查函数
function canEditUser(user) {
    if (!currentUser) return false;
    if (currentUser.role === 'ADMIN') return true;
    if (currentUser.role === 'DEPT_MANAGER') {
        // 部门管理员只能编辑自己部门的终端用户
        return user.role === 'END_USER' && manageableDepartments.includes(user.departmentId);
    }
    return false;
}

function canDeleteUser(user) {
    if (!currentUser) return false;
    if (currentUser.role === 'ADMIN') {
        // 系统管理员不能删除自己
        return user.id !== currentUser.id;
    }
    if (currentUser.role === 'DEPT_MANAGER') {
        // 部门管理员只能删除自己部门的终端用户
        return user.role === 'END_USER' && manageableDepartments.includes(user.departmentId);
    }
    return false;
}

// 辅助函数
function getRoleDisplayName(role) {
    const roleNames = {
        'ADMIN': '系统管理员',
        'DEPT_MANAGER': '部门管理员',
        'DISPATCHER': '调度员',
        'END_USER': '终端用户'
    };
    return roleNames[role] || role;
}

function getRoleBadgeColor(role) {
    const colors = {
        'ADMIN': 'danger',
        'DEPT_MANAGER': 'warning',
        'DISPATCHER': 'info',
        'END_USER': 'secondary'
    };
    return colors[role] || 'secondary';
}

function getStatusDisplayName(status) {
    const statusNames = {
        'AVAILABLE': '可用',
        'BUSY': '忙碌',
        'OFFLINE': '离线'
    };
    return statusNames[status] || status;
}

function getStatusBadgeColor(status) {
    const colors = {
        'AVAILABLE': 'success',
        'BUSY': 'warning',
        'OFFLINE': 'secondary'
    };
    return colors[status] || 'secondary';
}

// 显示成功提示
function showSuccess(message) {
    // 创建临时提示元素
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-success alert-dismissible fade show position-fixed';
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        <i class="bi bi-check-circle me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alertDiv);
    // 3秒后自动移除
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 3000);
}

// 显示错误提示
function showErrorAlert(message) {
    // 创建临时提示元素
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-danger alert-dismissible fade show position-fixed';
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        <i class="bi bi-exclamation-triangle me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alertDiv);
    // 5秒后自动移除
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 5000);
}

// 确认操作
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

// 根据权限控制UI显示
function setupPermissionControls() {
    const isAdmin = currentUser && currentUser.role === 'ADMIN';
    const isDeptManager = currentUser && currentUser.role === 'DEPT_MANAGER';
    // 控制创建用户按钮
    const createBtn = document.getElementById('createUserBtn');
    if (createBtn) {
        createBtn.style.display = (isAdmin || isDeptManager) ? 'block' : 'none';
    }
    // 控制角色选择
    const roleSelect = document.getElementById('role');
    if (roleSelect && isDeptManager) {
        // 部门管理员只能创建终端用户
        Array.from(roleSelect.options).forEach(option => {
            if (option.value !== 'END_USER') {
                option.disabled = true;
            }
        });
    }
    // 显示权限提示
    const permissionInfo = document.getElementById('permissionInfo');
    const permissionText = document.getElementById('permissionText');
    if (permissionInfo && permissionText) {
        permissionInfo.style.display = 'block';
        if (isAdmin) {
            permissionText.innerHTML = '<i class="bi bi-shield-check text-success"></i> 系统管理员：可以管理所有用户';
        } else if (isDeptManager) {
            permissionText.innerHTML = '<i class="bi bi-shield text-warning"></i> 部门管理员：只能管理本部门及下级部门的终端用户';
        } else {
            permissionText.innerHTML = '<i class="bi bi-shield-x text-danger"></i> 无用户管理权限';
        }
    }
} 